﻿
namespace SuperMarieApi.App.Controllers.Framework.XmlConfig.Service
{
    using System;
    using System.Web;

    using SuperMarieApi.App.Controllers.Framework.XmlConfig;
    using SuperMarieApi.App.Controllers.Framework.XmlConfig.Model;

    public class RuntimePropertiesHelper
    {
        /// <summary>
        ///  读取配置文件
        /// </summary>
        public RuntimeProperties loadConfig()
        {
            if (HttpContext.Current == null)
            {
                return this.loadConfig(XmlConfigUtils.GetXmlMapPath(Keys.RuntimeEnvironment));
            }
            RuntimeProperties model = CacheHelper.Get<RuntimeProperties>(Keys.CacheRuntimeEnvironment);
            if (model == null)
            {
                CacheHelper.Insert(Keys.CacheRuntimeEnvironment, this.loadConfig(XmlConfigUtils.GetXmlMapPath(Keys.RuntimeEnvironment)), XmlConfigUtils.GetXmlMapPath(Keys.RuntimeEnvironment));
                model = CacheHelper.Get<RuntimeProperties>(Keys.CacheRuntimeEnvironment);
            }
            return model;
        }

        /// <summary>
        ///  保存配置文件
        /// </summary>
        public RuntimeProperties saveConifg(RuntimeProperties model)
        {
            return this.saveConifg(model, XmlConfigUtils.GetXmlMapPath(Keys.FileSiteXmlConfing));
        }


        private static object lockHelper = new object();

        /// <summary>
        ///  读取站点配置文件
        /// </summary>
        public RuntimeProperties loadConfig(string configFilePath)
        {
            return (RuntimeProperties)SerializationHelper.Load(typeof(RuntimeProperties), configFilePath);
        }

        /// <summary>
        /// 写入站点配置文件
        /// </summary>
        private RuntimeProperties saveConifg(RuntimeProperties model, string configFilePath)
        {
            lock (lockHelper)
            {
                SerializationHelper.Save(model, configFilePath);
            }
            return model;
        }

        #region 赋值操作=================================
        protected void Get_Click()
        {
            RuntimeProperties model = this.loadConfig();
        }

        /// <summary>
        /// 保存配置信息
        /// </summary>
        protected void Save_Click(object sender, EventArgs e)
        {
            RuntimeProperties model = this.loadConfig();
            //TODO:修改model
            this.saveConifg(model);
        }
        #endregion
    }
}
